<template>
  <div>
    <resource ref="res" @setResource="setResource" @editSetResource="editSetResource"/>
    <play-video ref="video" :video-url="videoUrl"/>
    <common-select ref="comSel" @setSelectInfo="setSelectInfo"/>
    <el-form ref="form" :model="form.train"  :rules="rules" label-width="120px" style="margin: 5px;">
      <div class="dd-portlet">
        <div class="dd-title">
          <span>培训计划信息</span>
        </div>
        <div class="dd-body">
          <el-row>
            <el-col :span="8">
              <el-form-item label="培训名称" prop="trainName">
                <el-input v-model="form.train.trainName" maxlength="20" placeholder="培训名称"  style="width: 320px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="培训方式" class="dd-label" prop="planType">
                <el-select v-model="form.train.planType" style="width: 320px" clearable filterable placeholder="培训方式">
                  <el-option v-for="item in dicts" :key="item.id" :label="item.label" :value="item.value-0">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="培训考核" class="dd-label" prop="checkId">
                <el-select v-model="form.train.checkId" style="width: 320px" clearable filterable placeholder="培训考核">
                  <el-option v-for="item in checkList" :key="item.id" :label="item.checkName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="form.train.startTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期" style="width: 320px;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="form.train.endTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期" style="width: 320px;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="培训老师" class="dd-label" prop="trainTeacher">
                <el-input v-model="form.train.trainTeacher" maxlength="20" placeholder="培训老师"  style="width: 320px;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="培训介绍" class="dd-label" prop="trainDesc">
                <el-input type="textarea" v-model="form.train.trainDesc" rows="9" :autosize="{ minRows: 7, maxRows: 12}" maxlength="200"
                          placeholder="请输入培训简介,200字以内" style="width: 320px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="培训封面" class="dd-label" :line="true">
                <el-upload :line="true"
                  class="avatar-uploader"
                  :action="fileUploadUrl"
                  accept=".jpg,.jpeg,.png"
                  :show-file-list="false"
                  :on-success="themeHandleSuccess"
                   v-loading="themeLoading"
                  :before-upload="beforeThemeUpload">
                  <img v-if="themeUrl" :src="themeUrl" class="avatar"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="dd-title">
            <span>培训课程目录</span>
            <span class="marginleft">
              <el-popover placement="top-start" width="110" trigger="hover" content="新增课程目录">
                <el-button slot="reference" size="mini" type="success" icon="el-icon-plus" @click="addChapter()"
                           circle></el-button>
              </el-popover>
            </span>
          </div>
          <div>
            <el-card class="box-card" v-for="(item,index) in form.trainChapter" :key="index">
              <div slot="header" class="clearfix">
                <span>{{item.label}}</span>
                <el-button style="float: right; padding: 1px" type="text" @click="delChapter(index)">删除目录</el-button>
                <el-button style="float: right; padding: 1px" type="text" @click="editChapter(index)">编辑目录</el-button>
              </div>
              <el-row v-for="(resource,resourceIndex) in item.trainResourceList" :key="resourceIndex">
                <el-col :span="9">
                  <div>
                    <span><i class="el-icon-video-camera"></i></span>{{resource.resourceName}}
                  </div>
                </el-col>
                <el-col :span="3">
                  <div>{{resource.classHourStr}}</div>
                </el-col>
                <el-col :span="6">
                  <div><span>{{resource.resourceFileName}}</span></div>
                </el-col>
                <el-col :span="3">
                  <div><span>下载权限：</span>
                    <el-switch v-model="resource.isDownload" :active-value="1" :inactive-value="0"></el-switch>
                  </div>
                </el-col>
                <el-col :span="3">
                  <div class="buttonCss">
                    <el-popover placement="top-start" width="110" trigger="hover" content="编辑课程子目录">
                      <el-button slot="reference" size="mini" type="primary"
                                 @click="editResource(resource,index,resourceIndex)" icon="el-icon-edit" circle/>
                    </el-popover>
                    <el-popover placement="top-start" width="110" trigger="hover" content="删除课程子目录">
                      <el-button slot="reference" size="mini" type="danger" @click="delResource(index,resourceIndex)"
                                 icon="el-icon-delete" circle/>
                    </el-popover>
                    <el-popover placement="left-start" width="50" trigger="hover" content="播放">
                      <el-button slot="reference" size="mini" type="success" @click="playVideo(resource)"
                                 icon="el-icon-video-play" circle/>
                    </el-popover>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-bottom: -10px;">
                <el-col :span="12" :offset="11">
                  <div>
                    <el-popover placement="top-start" width="110" trigger="hover" content="新增课程子目录">
                      <el-button slot="reference" size="mini" type="success" @click="addResource(index)"
                                 icon="el-icon-plus" circle/>
                    </el-popover>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </div>
          <div class="dd-title">
            <span>培训人员</span>
          </div>
          <div class="dd-body" style="margin-top: -15px;">
            <el-row>
              <el-col :span="8">
                <el-form-item label="人员选择">
                  <el-link type="primary" @click="selectUser" :underline="false">人员选择</el-link>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="23">
               <el-form-item label="人员列表">
                 <div class="personDiv">
                   <el-tag v-for="user in form.trainUser" :key="user.userId" closable type="info"
                           @close="deletePersonnel(user)">{{user.userName}}
                   </el-tag>
                 </div>
               </el-form-item>
              </el-col>
            </el-row>

          </div>
          <div class="footer">
            <el-button type="info" @click="goBack" round>取消</el-button>
            <el-button :loading="loading" type="primary" @click="doSubmit" round>确认</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { add, info } from '@/api/business/trainPlan'
  import playVideo from '../components/playVideo'
  import resource from './resource'
  import { getUrl, getName, formatSeconds } from '@/utils/index'
  import commonSelect from '../components/commonSelect'
  import { getPostPageList } from '@/api/business/user'
  import { getCheckPageList } from '@/api/business/check'
  import initDict from '@/mixins/initDict'

  export default {
    components: { resource, playVideo, commonSelect },
    mixins: [initDict],
    data() {
      return {
        fileUploadUrl: process.env.FILE_UPLOAD,
        themeLoading:false,
        queryId: this.$route.query.id,
        loading: false,
        videoUrl: '',
        themeImage: [],
        trainFile: [],
        trainUser: [],
        checkList: [],
        themeUrl: null,
        resourceSort: 0,
        resource: {
          trainPlanId: '',
          resourceName: '',
          resourceFile: '',
          checkId: '',
          playType: '',
          resourceFileName: '',
          classHour: 0,
          classHourStr: '',
          sort: 0,
          isDownload: 0
        },
        chapterSort: 0,
        chapterList: {
          id: '',
          label: '', //章节名称
          trainId: '',
          sort: 0,
          trainResourceList: []
        },
        rules: {
          trainName: [
            { required: true, message: '请输入培训名称', trigger: 'blur' }
          ],
          planType: [
            { required: true, message: '请输选择培训方式', trigger: 'blur' }
          ],
          checkId: [
            { required: true, message: '请选择培训考核', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择开始时间', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '请选结束时间', trigger: 'blur' }
          ],
          trainDesc: [
            { required: true, message: '请填写培训简介', trigger: 'blur' }
          ],
          trainTeacher: [
            { required: true, message: '请填写培训老师', trigger: 'blur' }
          ],
        },
        form: {
          train: {
            id: null,
            trainName: '',
            themeImage: '',
            trainDesc: '',
            startTime: null,
            endTime: null
          },
          trainUser: [],
          trainChapter: []
        }
      }
    },
    created() {
      this.$nextTick(() => {
        this.initData()
        this.getDict('plan_type')
        if (this.queryId) {
          this.queryInfo()
        }
      })
    },
    methods: {
      getName,
      getUrl,
      formatSeconds,
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.doAdd()
          }
        })
      },
      doAdd() {
        if(this.themeUrl==null || this.themeUrl==""){
          this.$message({
            message: '请上传课培训封面！！',
            type: 'warning'
          })
          return
        }
        if (this.form.train.trainName === '') {
          this.$message({
            message: '请输入培训名称',
            type: 'warning'
          })
          return
        }
        if (this.form.trainUser.length === 0) {
          this.$message({
            message: '请选择培训参与人员',
            type: 'warning'
          })
          return
        }
        if (this.form.trainChapter.length === 0) {
          this.$message({
            message: '请添加培训课程目录',
            type: 'warning'
          })
          return
        }
        let resourceAlert = false
        let resourceInfo = ''
        this.form.trainChapter.forEach(item => {
          if (item.trainResourceList.length === 0) {
            resourceAlert = true
            resourceInfo = item.label
          }
        })
        if (resourceAlert) {
          this.$message({
            message: '请添加【' + resourceInfo + '】目录课程资源',
            type: 'warning'
          })
          return
        }
        add(this.form).then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.goBack()
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      initData() {
        this.getCheckList()
      },
      addChapter() {
        this.$prompt('请输入课程目录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.chapterSort++
          const chapterList = {
            id: '',
            label: value,
            trainId: '',
            sort: this.chapterSort,
            trainResourceList: []
          }
          this.form.trainChapter.push(chapterList)
        })
      },
      delChapter(index) {
        this.form.trainChapter.splice(index, 1)
      },
      editChapter(index) {
        this.$prompt('请输入课程目录', '提示', {
          confirmButtonText: '确定',
          inputValue: this.form.trainChapter[index].label,
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.form.trainChapter[index].label = value
        })
      },
      addResource(index) {
        this.$refs.res.dialog = true
        this.$refs.res.index = index
      },
      setResource(data, index) {
        if (this.form.trainChapter[index].trainResourceList.length !== 0) {
          data.sort = this.form.trainChapter[index].trainResourceList.length - 1
        }
        this.form.trainChapter[index].trainResourceList.push(data)
      },
      editSetResource(data, index, resourceIndex) {
        this.form.trainChapter[index].trainResourceList.splice(resourceIndex, 1, data)
      },
      playVideo(resource) {
        this.videoUrl = getUrl(resource.resourceFile)
        this.$refs.video.dialog = true
      },
      editResource(resource, index, resourceIndex) {
        this.$refs.res.index = index
        this.$refs.res.resourceIndex = resourceIndex
        this.$refs.res.resource = JSON.parse(JSON.stringify(resource))
        this.$refs.res.resourceFile = JSON.parse(resource.resourceFile)
        this.$refs.res.resource.classHourStr = formatSeconds(resource.classHour)
        this.$refs.res.dialog = true
        this.$refs.res.edit = true
      },
      delResource(index, resourceIndex) {
        this.form.trainChapter[index].trainResourceList.splice(resourceIndex, 1)
      },
      beforeThemeUpload(file) {
        var imgfileType="'image/jpeg','image/jpg','image/pjpeg','image/x-png','image/png'";
        const isJPG =imgfileType.indexOf(file.type )>0;
        if (!isJPG) {
          this.$message.error('上传课程封面图片只能是 jpg、png、jpeg 格式!')
          return false;
        }
        this.themeLoading=true
      },
      themeHandleSuccess(response, file, fileList) {
        this.form.train.themeImage = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.themeUrl = uploadFile.url
        this.form.train.themeImage.push(uploadFile)
        this.form.train.themeImage = JSON.stringify(this.form.train.themeImage)
        this.$refs.form.validateField('themeImage')
        this.themeLoading=false
      },
      queryInfo() {
        info(this.queryId).then(data => {
          this.form = data
          this.themeUrl = getUrl(data.train.themeImage)
          data.trainChapter.forEach(item => {
            item.trainResourceList.forEach(resource => {
              resource.resourceFileName = getName(resource.resourceFile)
              resource.classHourStr = formatSeconds(resource.classHour)
            })
          })
          this.form.train.classHourStr = formatSeconds(this.form.train.classHour)
          this.chapterSort = data.trainChapter.length
        })
      },
      selectUser() {
        this.$refs.comSel.dialog = true
      },
      deletePersonnel(user) {
        this.form.trainUser.splice(this.form.trainUser.indexOf(user), 1)
      },
      setSelectInfo(data) {
        if (data != null) {
          if (data.type === 4) {
            this.setUserInfo(data.data)
          } else {
            const params = this.getQueryParams(data)
            getPostPageList(params).then(data => {
              this.setUserInfo(data.content)
            })
          }
        }
      },
      getQueryParams(data) {
        const params = { size: 10000, roleCode: 'r_student' }
        const paramsIds = data.data.map(item => item.id)
        switch (data.type) {
          case 1:
            params.deptIds = paramsIds
            break
          case 2:
            params.jobs = paramsIds
            break
          case 3:
            params.specialtyIds = paramsIds
            break
        }
        return params
      },
      setUserInfo(data) {
        this.form.trainUser = []
        data.forEach(item => {
          const user = {
            userId: item.id,
            userName: item.name
          }
          this.form.trainUser.push(user)
        })
        this.form.trainUser = Array.from(new Set(this.form.trainUser))
      },
      goBack() {
        this.$router.go(-1)
      },
      getCheckList() {
        const params = { size: 10000,checkType:1 }
        getCheckPageList(params).then(data => {
          this.checkList = data.content
        })
      }
    }
  }
</script>

<style>
  .marginleft {
    margin-left: 20px;
  }

  .marginleft el-collapse-item {
    margin-left: 20px;
  }

  .el-collapse-item__header {
    font-weight: 800;
    font-size: 14px;
  }

  .el-row {
    margin-bottom: 10px;
  }

  .box-card {
    margin-bottom: 10px;
  }

  .box-card .clearfix span {
    font-weight: 800;
  }

  .buttonCss {
    text-align: center;
  }
</style>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .footer {
    height: 100px;
    width: 100%;
    text-align: center;
    bottom: 0;
    padding-top: 20px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 168px;
    height: 168px;
    line-height: 168px;
    text-align: center;
  }

  .avatar {
    width: 168px;
    height: 168px;
    display: block;
  }

  .personDiv {
    width: 100%;
    height: 200px;
    overflow: auto;
    border: 1px dashed #dcdfe6;
  }
  .el-tag.el-tag--info{
      margin-left: 5px
  }
  .el-tag + .el-tag {
    margin: 5px 10px;
  }

</style>
